<?php

namespace App\Imports;

use App\Models\Withdraw;
use App\Models\User;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\Importable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Brick\Math\BigDecimal;


class WithdrawImport
{

	public function query($rows)
	{
		// remove headrow.

		if (count($rows) <= 0) return;

		if (count($rows) > 500) return;

		foreach ($rows as $row) {
			DB::transaction(function () use ($row) {
				$status = isset($row[8]) ? $row[8] : null;
				$remark = isset($row[7]) ? $row[7] : null;
				$remark = str_replace("'","",$remark);
				$remark = (int)$remark;
				//sscanf($remark, "%d", $id);
				
				$withdraw = Withdraw::where('id', $remark)->where('status', "pending")->first();

				
				

				if ($withdraw) {
					if($status=="成功"){
						$withdraw->update([
							'status' => 'paid',
							'paid_at' => date("Y-m-d H:i:s",time()),
						]);
					}else{
						$user = User::find($withdraw->user_id);

						$data = ['withdraw_id' => $withdraw->id];
						account_balances($user)->plusFailedWithdrawPrincipal($withdraw->actual_amount, $data);
						account_balances($user)->plusFailedWithdrawCharge($withdraw->charge_amount, $data);
						$withdraw->update([
							'status' => 'returned',
							'paid_at' => date("Y-m-d H:i:s",time()),
							'remark' => $remark
						]);

					}
				}
			});
			usleep(50);
		}
	}



}
